package com.example.dbsample.service.impl;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.example.dbsample.context.ThreadLocalContext;
import com.google.common.collect.Sets;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.Set;

@Component
public class CustomTenantHandler implements TenantLineHandler {

    private static final Set<String> LU_FILTER_IGNORE_TABLE = Sets.newHashSet("lf_view", "lf_remote_info");

    private static final Set<String> BASE_IGNORE_TABLE = Sets.newHashSet("business_line", "data_bus", "model");

    // Expression & StringValue
    @Override
    public Expression getTenantId() {
        // 假设有个租户上下文，能够从中获取当前用户的租户
        String bizCode = ThreadLocalContext.getBizCode();
        // TODO 临时解决bizCode = null的问题
        bizCode = Optional.ofNullable(bizCode).orElse("");

        // 返回租户ID的表达式
        return new StringValue(bizCode);
    }

    @Override
    public String getTenantIdColumn() {
        return "biz_code";
    }

    @Override
    public boolean ignoreTable(String tableName) {
        if(isLuFilterTable(tableName) || isBaseTable(tableName)) {
            return true;
        }
        return false;
    }

    private boolean isBaseTable(String tableName) {
        Optional<String> first = BASE_IGNORE_TABLE.stream().filter(t -> t.equalsIgnoreCase(tableName)).findFirst();
        return first.isPresent();
    }

    private boolean isLuFilterTable(String tableName) {
        Optional<String> first = LU_FILTER_IGNORE_TABLE.stream().filter(e -> e.equalsIgnoreCase(tableName)).findFirst();
        return first.isPresent();
    }
}
